import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class Analyzer {
	
	StringBuffer buffer;
	File output;
	Writer outputWriter;
	private String currentId;
	private Map<String, String> quotes = new HashMap<String, String>();
	
	public Analyzer(File output) throws Exception {
		this.buffer = new StringBuffer();
		this.outputWriter = new FileWriter(output);
		this.output = output;
	}
	
	public void analyze(File file) throws Exception {
		FileInputStream fis = new FileInputStream(file);
		InputStreamReader isr = new InputStreamReader(fis, "UTF-16LE");
		BufferedReader br = new BufferedReader(isr);
		String read;
		int i = 0;
		while ((read = br.readLine()) != null) {
			if (i == 20) {
				String result = findBold(read);
				if (this.quotes.keySet().contains(this.currentId)) {
					
					System.out.println("\"" + result + "\" and \"" + this.quotes.get(this.currentId) + "\" match together.");
					String union;
					
					if(this.quotes.get(this.currentId).trim().matches(".+[.?!)]")) {
						union = result + this.quotes.get(this.currentId);
					} else {
						union = this.quotes.get(this.currentId) + result;
					}
					this.quotes.put(this.currentId, findBold(union));
					System.out.println("Union gives \"" + this.quotes.get(this.currentId) + "\"");
				} else {
					this.quotes.put(this.currentId, result);
				}
			} else if (i == 4) {
				this.currentId = read.substring(9);
			}
			i++;
		}
		br.close();
	}

	private String findBold(String read) {
		String result = read.replaceAll(":-\\)", "<b>").replaceAll(":-P", "</b>");
		return result;
	}
	
	private void writeFile() throws IOException {
		Iterator<String> it = this.quotes.values().iterator();
		while (it.hasNext()) {
			this.outputWriter.write(it.next() + "\r\n");
		}
	}
	
	public void finalize() throws Exception {
		this.outputWriter.close();
	}

	public File getOutput() throws IOException {
		writeFile();
		return output;
	}
}
